import 'dart:convert';
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import 'common_client.dart';
import 'common_colors.dart';
import 'data/goods_entity.dart';

class CaipuPage extends StatefulWidget {
  const CaipuPage({Key? key}) : super(key: key);

  @override
  State<CaipuPage> createState() => _CaipuPageState();
}

class _CaipuPageState extends State<CaipuPage> {
  List<String> cas = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
  Map<int, List<GoodsEntity>> allGoods = {};
  List<GoodsEntity> curGoods = [];
  int cueCate = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          onPressed: () => Get.back(),
          icon: Icon(
            Icons.arrow_back_ios,
            color: Colors.black,
          ),
        ),
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
        title: Text(
          "每日菜谱",
          style: TextStyle(
              fontSize: 18, color: Colors.black, fontWeight: FontWeight.w600),
        ),
      ),
      body: Stack(
        children: [
          _midContent(),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _getGoods();
  }

  _midContent() {
    return Positioned(
        top: 0.5,
        bottom: 0,
        left: 0,
        right: 0,
        child: Flex(
          direction: Axis.horizontal,
          children: [
            Expanded(
                flex: 2,
                child: DecoratedBox(
                  decoration: BoxDecoration(color: CommonColor.colorF5),
                  child: ListView.builder(
                    itemCount: cas.length,
                    itemBuilder: (cxt, index) => _sinCategory(index),
                  ),
                )),
            Expanded(
                flex: 5,
                child: DecoratedBox(
                  decoration: BoxDecoration(color: Colors.white),
                  child: ListView.separated(
                    itemCount: curGoods.length,
                    itemBuilder: (cxt, index) => _sinGoods(index),
                    separatorBuilder: (cxt, index) => Divider(
                      height: 1,
                      color: CommonColor.colorEE,
                    ),
                  ),
                ))
          ],
        ));
  }

  _sinCategory(int index) {
    return GestureDetector(
      child: Container(
        height: 55,
        color: cueCate == index ? Colors.white : CommonColor.colorF5,
        alignment: Alignment.center,
        child: Text(cas[index]),
      ),
      onTap: () => setState(() {
        cueCate = index;
        curGoods.clear();
        curGoods.addAll(allGoods[cueCate] ?? []);
      }),
    );
  }

  _sinGoods(int index) {
    var good = curGoods[index];
    return Container(
      height: 90,
      alignment: Alignment.center,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: 12,
          ),
          CachedNetworkImage(
            height: 65,
            width: 65,
            imageUrl: good.image ?? '',
            imageBuilder: (context, imageProvider) => Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                image: DecorationImage(
                  image: imageProvider,
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
          SizedBox(
            width: 12,
          ),
          RichText(
              text: TextSpan(children: [
            TextSpan(
                text: good.name ?? "商品名称",
                style: TextStyle(
                    color: CommonColor.color33,
                    fontSize: 15,
                    height: 2,
                    fontWeight: FontWeight.w600)),
            TextSpan(
              text: "\n",
            ),
            TextSpan(
              text: "\n",
            ),
            TextSpan(
                text: '¥ ',
                style: TextStyle(
                    color: CommonColor.colorOri, height: 2, fontSize: 10)),
            TextSpan(
                text: good.price.toString(),
                style: TextStyle(
                    color: CommonColor.colorOri, height: 2, fontSize: 15))
          ])),
          Spacer(),
          Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              SizedBox(
                height: 2,
              )
            ],
          ),
          SizedBox(
            width: 10,
          )
        ],
      ),
    );
  }

  _getGoods() async {
    try {
      EasyLoading.show(status: 'loading...');
      allGoods.clear();
      var res = await CommonClient().getGoods(1, 100);
      List<dynamic> data = jsonDecode(res.data ?? "");
      List<GoodsEntity> gs = [];
      if (data != null) {
        var rng = Random();
        data.forEach((element) {
          var sin = GoodsEntity.fromJson(element);
          sin.category = rng.nextInt(7);
          gs.add(sin);
        });
        allGoods = groupBy(gs, (p0) => p0.category ?? 0);
      }
      setState(() {
        curGoods.clear();
        curGoods.addAll(allGoods[cueCate] ?? []);
      });
      print(res);
    } catch (e) {
      print(e);
    } finally {
      EasyLoading.dismiss();
    }
  }
}
